
import { addreq, setRefreshToken } from './setRefreshToken'

const myRequest = (url, method, data, header) => {
	return new Promise((resolve, reject) => {

		if (uni.getStorageSync('getA')) {
			let a = uni.getStorageSync('getA')
			a++
			uni.setStorageSync('getA', a)
		} else {
			uni.setStorageSync('getA', 1)
		}
		if (uni.getStorageSync('getA') === 1) {
			uni.showLoading({ title: '加载中', mask: true })
		}
		let token = uni.getStorageSync('token')
		let version = uni.getStorageSync('version')
		let machine = uni.getStorageSync('machine')

		uni.request({
			url: url,
			method: method,
			data: {
				// #ifdef MP-WEIXIN
				clientType: 'WECHAT_MP',
				// #endif
				// #ifdef MP-TOUTIAO
				clientType: 'DOUYIN_MP',
				// #endif
				// #ifndef MP
				clientType: 'APP',
				// #endif
				...data
			},
			header: {
				'Referer': 'https://www.xdyy100.com',
				'accessToken': token,
				'version': version,
				'Sign': machine.deviceId,
				'Os-Name': machine.osName,
				'Os-Version': machine.osVersion,
				'Brand': machine.brand,
				'Device-Model': machine.deviceModel,
				// #ifdef MP-WEIXIN
				'Client-Type': 'WECHAT_MP',
				// #endif
				// #ifdef MP-TOUTIAO
				'Client-Type': 'DOUYIN_MP',
				// #endif
				// #ifndef MP
				'Client-Type': 'APP',
				'User-Agent': machine.ua,
				// #endif
				'Content-type': 'application/x-www-form-urlencoded',
				...header
			},
			success: (res) => {
				if (res.statusCode === 302) {
					resolve(res.header.location)
				} else if (res.data.code === 200) {
					resolve(res.data)
				} else if (res.data.status === 403) {
					addreq({ url, method, data, header })
					setRefreshToken()
				} else {
					setTimeout(() => {
						uni.showToast({ icon: 'none', title: res.data.msg, mask: true })
						resolve(res.data)
					}, 0)
				}
			},
			fail: (err) => {
				uni.showToast({ icon: 'none', title: '接口请求失败', mask: true })
				reject(err)
			},
			complete: () => {
				let b = uni.getStorageSync('getA')
				b--
				uni.setStorageSync('getA', b)
				if (b <= 0) {
					uni.hideLoading()
					uni.setStorageSync('getA', 0)
				}
			}
		})
	})
}

export default myRequest
